var express = require('express');
var router = express.Router();
const { Article } = require('../../models');
const { Op } = require('sequelize');

// import { success, NotFoundError, failure } from '../../utils/response';
const { NotFoundError } = require('../../utils/errors');
const { success, failure } = require('../../utils/responses');

/* GET home page. */
router.get('/', async function (req, res, next) {
    try {
        // return res.json({currentUser: req.user})
        const query = req.query;
        // 页和每页现实几条数据
        const currentPage = Math.abs(Number(query.currentPage)) || 1;
        const pageSize = Math.abs(Number(query.pageSize)) || 10;

        const offset = (currentPage - 1) * pageSize;

        const condition = {
            order: [['id', 'DESC']],
            offset: offset,
            limit: pageSize
        }
        if (query.title) {
            condition.where = {
                title: {
                    [Op.like]: `%${query.title}%`
                }
            }
        }
        console.log('condition->',condition)
        // const article = await Article.findAll(condition);
        const { count, rows } = await Article.findAndCountAll(condition);
        success(
            res,
            '查询文章列表成功',
            {
                article: rows,
                pagination: {
                    total: count,
                    currentPage,
                    pageSize
                }
            }
        )
    } catch (error) {
        failure(res, error)
    }
});

// 查询文章详情
router.get('/:id', async function (req, res, next) {
    try {
        const article = await getArticle(req);
        success(
            res,
            '查询文章成功',
            {article}
        )

    } catch (error) {
        failure(res, error)
    }
});


// 新建文章
router.post('', async function (req, res, next) {
    try {
        const body = filterBody(req.body)
        const article = await Article.create(body)
        success(
            res,
            '创建文章成功',
            {article}
        )
    } catch (error) {
        failure(res, error)
        // if (error.name === 'SequelizeValidationError') {
        //     const errors = error.errors.map(item => item.message)
        //     res.json({
        //         code: 400,
        //         message: '请求参数错误',
        //         error: errors
        //     })
        // }else {
        //     res.json({
        //         code: 500,
        //         message: '创建文章失败',
        //         error: [error.message]
        //     })
        // }
    }
});

// 删除文章
router.delete('/:id', async function (req, res, next) {
    try {
        // const { id } = req.params;
        // const article = await Article.findByPk(id);
        // console.log('article=>',article)
        // if (article) {
        //     await article.destroy()
        //     res.json({
        //         code: 200,
        //         message: '删除文章成功',
        //     })
        // } else {
        //     res.json({
        //         code: 404,
        //         message: '文章未找到',
        //     })
        // }
        const article = await getArticle(req);
        await article.destroy()
        success(
            res,
            '删除文章成功'
        )
    } catch (error) {
        failure(res, error)
    }
});

// 更新文章
router.put('/:id', async function (req, res, next) {
    try {
        const article = await getArticle(req);
        const body = filterBody(req.body)
        await article.update(body)
        success(
            res,
            '更新文章成功', {
                article
            }
        )
    } catch (error) {
        failure(res, error)
    }
});

// 过滤body 和 title
const filterBody = (body)=>{
    return {
        title: body.title,
        content: body.content
    }
}


/**
 * 查询当前文章
 * @param {*} req 
 */
async function getArticle(req) {
    const { id } = req.params;
    console.log('id==>',id)
    const article = await Article.findByPk(id);
    console.log('啊啊啊-->',article)
    if (!article) {
        throw new NotFoundError(`ID: ${id}的文章未找到`)
    }
    return article;
}

module.exports = router;
